//
//  BCBaseRequestOperation.m
//  BCBaseNetworking
//
//  Created by Basic on 15/3/20.
//  Copyright (c) 2015年 Basic. All rights reserved.
//  网络请求基类
//

#import "BCBaseRequestOperation.h"

@interface BCBaseRequestOperation()
@property (nonatomic, getter = isFinished, readwrite)   BOOL finished;/**< 是否在完成 */
@property (nonatomic, getter = isExecuting, readwrite)  BOOL executing;/**< 是否在执行 */
@end


@implementation BCBaseRequestOperation
@synthesize finished  = _finished;
@synthesize executing = _executing;

#pragma mark - system
- (instancetype)init
{
    self = [super init];
    if (self) {
        _finished  = NO;
        _executing = NO;
    }
    return self;
}
/**
 *  初始化
 *
 *  @param task 需要执行的Session task
 *
 *  @return instancetype
 */
- (instancetype)initWithSessionTask:(NSURLSessionTask *)task
{
    self = [super init];
    if (self) {
        _pacSessionTask = task;
        _finished  = NO;
        _executing = NO;
    }
    return self;
}
- (void)start
{
    if(!_pacSessionTask){
        NSAssert(NO, @"BCBaseRequestOperation session task is nil");
        self.finished = YES;
        return;
    }
    if ([self isCancelled]) {
        self.finished = YES;
        return;
    }
    self.executing = YES;
    [_pacSessionTask resume];
}
- (void)cancel {
    [super cancel];

    // 如果正在执行中则表示已经start过，可以将isFinished设为yes
    if (self.isExecuting) {
        self.finished = YES;
        self.executing = NO;
    }
    if (_pacSessionTask) {
        [_pacSessionTask cancel];
    }
}
-(void)dealloc
{
    _requestModel = nil;
    _responseModel = nil;
//    BCLog(@"BCBaseRequestOperation dealloc");
}

#pragma mark - NSOperation methods
- (BOOL)isExecuting
{
    @synchronized(self) {
        return _executing;
    }
}
- (BOOL)isFinished
{
    @synchronized(self) {
        return _finished;
    }
}
- (void)setExecuting:(BOOL)executing
{
    if (_executing != executing) {
        [self willChangeValueForKey:@"isExecuting"];
        @synchronized(self) {
            _executing = executing;
        }
        [self didChangeValueForKey:@"isExecuting"];
    }
}
- (void)setFinished:(BOOL)finished
{
    [self willChangeValueForKey:@"isFinished"];
    @synchronized(self) {
        if (_finished != finished) {
            _finished = finished;
        }
    }
    [self didChangeValueForKey:@"isFinished"];
}

#pragma mark - 请求完成回调

/**
 *  请求operation完成的回调
 *
 *  @param success     是否成功
 */
- (void)onRequestOpeationComplate:(BOOL )success
{
    if(success){
        [_requestModel onReponseSuccessAction:self withResponse:_responseModel];
    }
    else{
        [_requestModel onReponseErrorAction:self withResponse:_responseModel];
    }
    //通知operation 完成
    self.executing = NO;
    self.finished  = YES;
}

@end
